{% extends 'base.html' %}

{% block title %}{{ movie.title }} - 电影推荐系统{% endblock %}

{% block content %}
<div class="row">
    <div class="col-md-4">
        <img src="{{ movie.poster_url|default:'https://via.placeholder.com/300x450?text=暂无海报' }}" 
             class="img-fluid rounded" alt="{{ movie.title }}">
    </div>
    <div class="col-md-8">
        <h1>{{ movie.title }} <small class="text-muted">({{ movie.year }})</small></h1>
        <div class="mb-3">
            {% for genre in movie.genres.all %}
            <span class="badge bg-secondary">{{ genre.name }}</span>
            {% endfor %}
        </div>
        <div class="mb-3">
            <div class="d-flex align-items-center">
                <h4 class="me-2">评分: {{ movie.average_rating|floatformat:1 }}/5</h4>
                <div class="rating-stars">
                    {% for i in "12345" %}
                    <span class="star {% if forloop.counter <= movie.average_rating %}filled{% endif %}">★</span>
                    {% endfor %}
                </div>
            </div>
        </div>
        <h3>剧情简介</h3>
        <p>{{ movie.description }}</p>
        
        {% if user.is_authenticated %}
        <div class="card mt-4">
            <div class="card-header">
                {% if user_rating %}
                编辑你的评分
                {% else %}
                为这部电影评分
                {% endif %}
            </div>
            <div class="card-body">
                <form method="post">
                    {% csrf_token %}
                    <div class="mb-3">
                        <label for="{{ form.rating.id_for_label }}" class="form-label">评分</label>
                        {{ form.rating }}
                    </div>
                    <div class="mb-3">
                        <label for="{{ form.comment.id_for_label }}" class="form-label">评论</label>
                        {{ form.comment }}
                    </div>
                    <button type="submit" class="btn btn-primary">提交评分</button>
                </form>
            </div>
        </div>
        {% else %}
        <div class="alert alert-info mt-4">
            请<a href="{% url 'login' %}">登录</a>后为这部电影评分。
        </div>
        {% endif %}
    </div>
</div>

<div class="card mt-4">
    <div class="card-header">
        <ul class="nav nav-tabs card-header-tabs" id="movieAnalysisTabs" role="tablist">
            <li class="nav-item" role="presentation">
                <button class="nav-link active" id="ai-analysis-tab" data-bs-toggle="tab" data-bs-target="#ai-analysis" type="button" role="tab" aria-controls="ai-analysis" aria-selected="true">AI分析</button>
            </li>
            <li class="nav-item" role="presentation">
                <button class="nav-link" id="similar-movies-tab" data-bs-toggle="tab" data-bs-target="#similar-movies" type="button" role="tab" aria-controls="similar-movies" aria-selected="false">相似电影</button>
            </li>
        </ul>
    </div>
    <div class="card-body">
        <div class="tab-content" id="movieAnalysisTabContent">
            <div class="tab-pane fade show active" id="ai-analysis" role="tabpanel" aria-labelledby="ai-analysis-tab">
                <div id="aiAnalysisContent">
                    <div class="text-center py-5">
                        <div class="spinner-border text-primary" role="status">
                            <span class="visually-hidden">加载中...</span>
                        </div>
                        <p class="mt-2">正在生成AI分析...</p>
                    </div>
                </div>
            </div>
            <div class="tab-pane fade" id="similar-movies" role="tabpanel" aria-labelledby="similar-movies-tab">
                <div id="similarMoviesContent">
                    <div class="text-center py-5">
                        <div class="spinner-border text-primary" role="status">
                            <span class="visually-hidden">加载中...</span>
                        </div>
                        <p class="mt-2">正在查找相似电影...</p>
                    </div>
                </div>
            </div>
        </div>
    </div>
</div>

<div class="mt-5">
    <h3>用户评价</h3>
    {% if movie.rating_set.all %}
    <div class="list-group">
        {% for rating in movie.rating_set.all %}
        <div class="list-group-item">
            <div class="d-flex justify-content-between align-items-center">
                <h5 class="mb-1">{{ rating.user.username }}</h5>
                <div class="rating-stars">
                    {% for i in "12345" %}
                    <span class="star {% if forloop.counter <= rating.rating %}filled{% endif %}">★</span>
                    {% endfor %}
                </div>
            </div>
            {% if rating.comment %}
            <p class="mb-1 mt-2">{{ rating.comment }}</p>
            {% endif %}
            <small class="text-muted">{{ rating.created_at|date:"Y-m-d H:i" }}</small>
        </div>
        {% endfor %}
    </div>
    {% else %}
    <div class="alert alert-light">
        暂无用户评价，成为第一个评价这部电影的用户吧！
    </div>
    {% endif %}
</div>
{% endblock %}

{% block scripts %}
<script>
document.addEventListener('DOMContentLoaded', function() {
    // 评分星级效果
    const ratingInput = document.querySelector('#id_rating');
    if (ratingInput) {
        ratingInput.classList.add('form-select');
    }
    
    // 加载AI电影分析
    const aiAnalysisTab = document.getElementById('ai-analysis-tab');
    const similarMoviesTab = document.getElementById('similar-movies-tab');
    const aiAnalysisContent = document.getElementById('aiAnalysisContent');
    const similarMoviesContent = document.getElementById('similarMoviesContent');
    
    // 获取电影ID
    const movieId = {{ movie.id }};
    
    // 加载AI分析内容
    async function loadAIAnalysis() {
        if (aiAnalysisContent.dataset.loaded === 'true') {
            return; // 已加载，不重复请求
        }
        
        try {
            const response = await fetch(`/movies/api/ai-movie-analysis/${movieId}/`);
            if (!response.ok) {
                throw new Error('网络响应不正常');
            }
            
            const data = await response.json();
            
            // 格式化分析内容，处理换行符
            const formattedAnalysis = data.analysis.replace(/\n/g, '<br>');
            
            aiAnalysisContent.innerHTML = `<div class="movie-ai-analysis">${formattedAnalysis}</div>`;
            aiAnalysisContent.dataset.loaded = 'true';
            
        } catch (error) {
            console.error('加载AI分析出错:', error);
            aiAnalysisContent.innerHTML = `
                <div class="alert alert-warning">
                    <p>抱歉，无法加载AI分析内容。</p>
                    <button class="btn btn-sm btn-outline-primary mt-2" onclick="loadAIAnalysis()">重试</button>
                </div>
            `;
        }
    }
    
    // 加载相似电影
    async function loadSimilarMovies() {
        if (similarMoviesContent.dataset.loaded === 'true') {
            return; // 已加载，不重复请求
        }
        
        try {
            const response = await fetch(`/movies/api/ai-similar-movies/?title=${encodeURIComponent('{{ movie.title }}')}`)
            if (!response.ok) {
                throw new Error('网络响应不正常');
            }
            
            const data = await response.json();
            
            if (!data.similar_movies || data.similar_movies.length === 0) {
                similarMoviesContent.innerHTML = `
                    <div class="alert alert-info">
                        没有找到相似电影推荐。
                    </div>
                `;
                return;
            }
            
            // 创建相似电影卡片
            let moviesHTML = '<div class="row">';
            
            data.similar_movies.forEach(movie => {
                moviesHTML += `
                    <div class="col-md-4 mb-4">
                        <div class="card h-100">
                            <div class="card-body">
                                <h5 class="card-title">${movie.title} (${movie.year})</h5>
                                <p class="card-text small">${movie.similarity_reason || '推荐理由未提供'}</p>
                                <a href="/movies/?query=${encodeURIComponent(movie.title)}" class="btn btn-sm btn-outline-primary">查找此电影</a>
                            </div>
                        </div>
                    </div>
                `;
            });
            
            moviesHTML += '</div>';
            similarMoviesContent.innerHTML = moviesHTML;
            similarMoviesContent.dataset.loaded = 'true';
            
        } catch (error) {
            console.error('加载相似电影出错:', error);
            similarMoviesContent.innerHTML = `
                <div class="alert alert-warning">
                    <p>抱歉，无法加载相似电影推荐。</p>
                    <button class="btn btn-sm btn-outline-primary mt-2" onclick="loadSimilarMovies()">重试</button>
                </div>
            `;
        }
    }
    
    // 根据选项卡切换加载内容
    aiAnalysisTab.addEventListener('shown.bs.tab', loadAIAnalysis);
    similarMoviesTab.addEventListener('shown.bs.tab', loadSimilarMovies);
    
    // 默认加载AI分析
    loadAIAnalysis();
});
</script>
{% endblock %} 